import UIKit
import SnapKit
import FDTemplateLayoutCell
import Alamofire


class ChatMessageViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate{
    var retques: DataStreamRequest?
    var inputTextField:CustomTextField!
    var tableView:UITableView!
    let cellIdentifier = "message_cell"
    var list:[Message] = []
    var toolBar: UIView!
    //底部工具栏下约束
    var toolbarBottomConstraint: Constraint?
    var tableViewBottomConstraint: Constraint?
    var inputTextFieldRightConstraint: Constraint?
    let sendButton = UIButton()
    let voiceButton = UIButton()
    let refreshButton = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "聊天"
        self.view.backgroundColor = commonBackgroundColor
        setupSendPanel()
        tableView = UITableView(frame: .zero)
        tableView.register(MessageCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.backgroundColor = .clear
        self.tableView.delegate = self
        self.tableView.keyboardDismissMode = .onDrag
        self.tableView.dataSource = self
        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.separatorStyle = .none
        self.tableView.autoresizesSubviews = false
        self.tableView.estimatedSectionHeaderHeight = 0
        self.tableView.estimatedSectionFooterHeight = 0
        self.view.addSubview(tableView)
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.view).offset(32)
            self.tableViewBottomConstraint = make.bottom.equalTo(self.toolBar.snp.top).offset(-12).constraint
            make.width.equalTo(self.view)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        inputTextField.addTarget(self, action:#selector(inputTextFieldChange(textField: )), for:UIControl.Event.editingChanged)
        
        
        // 声明一个 UITapGestureRecognizer 识别手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
        
        // 将手势添加到视图上
        view.addGestureRecognizer(tapGesture)
    }
    
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        
        if !list.isEmpty{
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2){
                let indexPath = IndexPath(row: self.tableView.numberOfRows(inSection: 0) - 1, section: 0)
                self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
            }
            
            
        }
    }
    
    @objc func hideKeyboard() {
        // 在点击空白处时隐藏键盘
        view.endEditing(true)
    }
    
    @objc func  inputTextFieldChange(textField:UITextField) {
        if let text = textField.text,!text.isEmpty{
            sendButton.isHidden = false
            voiceButton.isHidden = true
            self.inputTextFieldRightConstraint?.update(offset: -56)
        }else{
            sendButton.isHidden = true
            voiceButton.isHidden = false
            self.inputTextFieldRightConstraint?.update(offset: -48)
        }
    }
    
    @objc func keyboardWillHide(notification: NSNotification) {
        
        //改变下约束
        self.toolbarBottomConstraint?.update(offset: 0)
        self.tableViewBottomConstraint?.update(offset: 0)
        
    }
    
    @objc func keyboardWillAppear(notification: NSNotification) {
        
        
        if let userInfo = notification.userInfo{
            
            let keyboardinfo = userInfo[UIResponder.keyboardFrameEndUserInfoKey]
            let keyboardheight: CGFloat = (keyboardinfo as AnyObject).cgRectValue.size.height
            
            let offset =  -(keyboardheight - self.view.safeAreaInsets.bottom)
            //改变下约束
            self.toolbarBottomConstraint?.update(offset:offset)
            self.tableViewBottomConstraint?.update(offset: 0)
            
        }
    }
    
    func addQuestion(_ prompt:String){
        let message = Message(question: prompt,isQuestion: true,refreshChat: false)
        list.append(message)
        
    }
    
    func addAnswer(prompt:String,answer: String?){
        let message = Message(question: prompt,answer:answer,isQuestion: false,refreshChat: false)
        list.append(message)
        
    }
    
    func setupSendPanel(){
        
        
        
        toolBar = UIView()
        toolBar.backgroundColor = .white
        
        
        refreshButton.addTarget(self, action:#selector(refreshChat) ,
                                for:UIControl.Event.touchUpInside)
        refreshButton.setImage(UIImage(systemName: "goforward"), for: .normal)
        refreshButton.tintColor = .black
        refreshButton.contentVerticalAlignment = .fill
        refreshButton.contentHorizontalAlignment = .fill
        refreshButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
        toolBar.addSubview(refreshButton)
        
        
        inputTextField = CustomTextField()
        inputTextField.keyboardAppearance = .light
        inputTextField.backgroundColor = commonBackgroundColor
        inputTextField.textColor=UIColor.black
        inputTextField.font=UIFont.systemFont(ofSize: 14, weight: .regular)
        inputTextField.layer.cornerRadius = 24.0
        inputTextField.attributedPlaceholder = NSAttributedString(string: "问我任何问题", attributes: [NSAttributedString.Key.foregroundColor : UIColor.gray])
        inputTextField.returnKeyType = UIReturnKeyType.send
        inputTextField.addLeftTextPadding(12)
        inputTextField.clearButtonMode = .whileEditing
        inputTextField.rightView?.backgroundColor = .primaryColor
        inputTextField.delegate=self
        toolBar.addSubview(inputTextField)
        self.view.addSubview(toolBar)
        
        sendButton.isHidden = true
        sendButton.addTarget(self, action:#selector(sendMessage) ,
                             for:UIControl.Event.touchUpInside)
        let image = UIImage(systemName: "paperplane.circle.fill")
        sendButton.setImage(image, for: .normal)
        sendButton.tintColor = .primaryColor
        sendButton.contentVerticalAlignment = .fill
        sendButton.contentHorizontalAlignment = .fill
        sendButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
        toolBar.addSubview(sendButton)
        
        
        
        voiceButton.addTarget(self, action:#selector(showVoiceView) ,
                              for:UIControl.Event.touchUpInside)
        voiceButton.setImage(UIImage(systemName: "mic"), for: .normal)
        voiceButton.tintColor = .black
        voiceButton.contentVerticalAlignment = .fill
        voiceButton.contentHorizontalAlignment = .fill
        voiceButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        
        toolBar.addSubview(voiceButton)
        
        
        
        
        
        
        toolBar.snp.makeConstraints { make in
            make.left.right.equalTo(self.view)
            make.height.equalTo(60)
            self.toolbarBottomConstraint = make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).constraint
        }
        sendButton.snp.makeConstraints { make in
            make.right.equalTo(toolBar).offset(-12)
            make.width.height.equalTo(36)
            make.centerY.equalTo(toolBar)
        }
        
        voiceButton.snp.makeConstraints { make in
            make.right.equalTo(toolBar).offset(-12)
            make.width.equalTo(26)
            make.height.equalTo(30)
            make.centerY.equalTo(toolBar)
        }
        
        refreshButton.snp.makeConstraints { make in
            make.left.equalTo(toolBar).offset(12)
            make.width.equalTo(26)
            make.height.equalTo(26)
            make.centerY.equalTo(toolBar)
        }
        
        inputTextField.snp.makeConstraints { make in
            make.left.equalTo(refreshButton.snp.right).offset(12)
            self.inputTextFieldRightConstraint = make.right.equalTo(toolBar).offset(-48).constraint
            make.height.equalTo(48)
            make.centerY.equalTo(toolBar)
        }
        
    }
    
    @objc func sendMessage(){
        if let prompt = inputTextField.text,prompt != ""{
            addQuestion(prompt)
            addAnswer(prompt: prompt, answer: "")
            self.tableView.reloadData()
            inputTextField.text = ""
            startSSE(prompt: prompt, rolePrompt: "")
        }else{
            self.view.makeToast("请输入您的问题",position: .center)
        }
        
        hideKeyboard()
        
        
//        addQuestion("你会做阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad什么？")
//        addAnswer(prompt: "dddd", answer: "")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        addQuestion("你会做什么？")
//        addAnswer(prompt: "dddd", answer: "阿基德拉胯京东方拉达克随机发拉萨的会计法拉卡萨电极法ad")
//        self.tableView.reloadData()
    }
    
    @objc func showVoiceView(){
    }
    
    @objc func refreshChat(){
    }
    
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
        return [NSAttributedString.Key.foregroundColor: UIColor.black]
    }
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! MessageCell
        
        cell.bindViewModel(list[indexPath.row])
        cell.selectionStyle = .none
        return cell
    }
    
    
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        sendMessage()
        return true
    }
    
    
    func startSSE(prompt: String,rolePrompt: String) {
        
        
        var components = URLComponents(string: "\(baseUrl)chatgpt/chat/sseV2")
        
        
        // 创建URL参数
        let promptItem = URLQueryItem(name: "prompt", value: prompt)
        let rolePromptItem = URLQueryItem(name: "rolePrompt", value: rolePrompt)
        
        
        // 将URL参数添加到URLComponents对象中
        components?.queryItems = [promptItem,rolePromptItem]
        
        
//        var receivedData = ""
        var msgIndex = 0
        
        if let url = components?.url {
            // 使用拼接好的URL进行网络请求或其他操作
            print("startSSEstartSSEstartSSE:\(prompt)")
            
            
            self.retques = AFManager.sharedInstance.manager.eventSourceRequest(url, lastEventID: "0").responseEventSource { eventSource in
                switch eventSource.event {
                case .message(let message):
                    
                    if let msg = message.data{
                        
                        msgIndex += 1
                        if msg.isChinese(){
//                            receivedData.append("\(msg)")
                            self.list.last?.answer?.append("\(msg)")
                        }else{
//                            receivedData.append("\(msg) ")
                            self.list.last?.answer?.append("\(msg) ")
                        }
                        
//                        self.list.last?.answer = receivedData
                        print("ddddddddddd"+(self.list.last?.answer! ?? "ttt"))
                        
//                        if let index = self.list.lastIndex(where: { $0.question == prompt }) {
//                        UITableView.performWithoutAnimation {
//                            self.tableView.performBatchUpdates {
                        
                        UIView.setAnimationsEnabled(false)
                        self.tableView.beginUpdates()
//                        self.tableView.reloadRows(at: [IndexPath.init(row: self.list.count - 1, section: 0)], with: .none)
                        self.tableView.reloadData()
                        self.tableView.endUpdates()
                        
                              
                                
//                            }
                            
//                        }
                        if msgIndex % 3 == 0{
//                            if self.isLastSectionVisible() == true {
//                                self.tableView.scrollToBottom(animated: true)
                            self.tableView.scrollToLast(at: .bottom, animated: true)
//                                self.tableView.scrollToLastItem(animated: true)
                            }
//                        }
//                        }
                        
                        
                        
                        
                    }else{
                        if let answer = self.list.last?.answer, answer != ""{
                            if !answer.hasSuffix("\n"){
                                self.list.last?.answer?.append("\n")
                            }
                        }
                    }
                    print("msg=\(message)")
                case .complete(_):
//                    UITableView.performWithoutAnimation {
//                        self.tableView.reloadRows(at: [IndexPath.init(row: self.list.count - 1, section: 0)], with: .none)
//                    }
//                    self.tableView.scrollToBottom(animated: true)
                    //                    self.messageInputBar.sendButton.stopAnimating()
                    //                    self.messageInputBar.inputTextView.placeholder = "与AI对话"
                    //                    if let index = self.messageList.lastIndex(where: { $0.sentDate == senderDate }) {
                    //                        UICollectionView.performWithoutAnimation {
                    //                            self.messagesCollectionView.reloadItems(at: [IndexPath(index: index)])
                    //                        }
                    //
                    //
                    //                        if self.isLastSectionVisible() == true {
                    //                            self.messagesCollectionView.scrollToLastItem(animated: true)
                    //                        }
                    //                    }
                    //                    if receivedData.contains("免费提问次数已用完"){
                    //                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1){
                    //                            let detailViewController = VipViewController()
                    //                            detailViewController.fromPage = "聊天-\(prompt)"
                    //                            self.navigationController?.pushViewController(detailViewController, animated: true)
                    //                        }
                    //
                    //                    }
                    print("completion")
                }
            }
        }
    }
    
    func isLastSectionVisible() -> Bool {
        guard !list.isEmpty else { return false }
        
        let lastIndexPath = IndexPath(item: 0, section: list.count - 1)
        return ((self.tableView.indexPathsForVisibleRows?.contains(lastIndexPath)) != nil)
    }
}
extension UITextField {
    
    /// 添加左内边距
    public func addLeftTextPadding(_ blankSize: CGFloat) {
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: blankSize, height: frame.height)
        self.leftView = leftView
        self.leftViewMode = UITextField.ViewMode.always
    }
    
}

class CustomTextField: UITextField {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        for view in subviews {
            if let button = view as? UIButton {
                button.setImage(button.image(for: .normal)?.withRenderingMode(.alwaysTemplate), for: .normal)
                button.tintColor = .black
            }
        }
    }
}
public extension UITableView {
    
    func scrollToFirst(at scrollPosition: UITableView.ScrollPosition, animated: Bool) {
        guard numberOfSections > 0 else { return }
        guard numberOfRows(inSection: 0) > 0 else { return }
        let indexPath = IndexPath(item: 0, section: 0)
        scrollToRow(at: indexPath, at: scrollPosition, animated: animated)
    }
    
    func scrollToLast(at scrollPosition: UITableView.ScrollPosition, animated: Bool) {
        guard numberOfSections > 0 else { return }
        let lastSection = numberOfSections - 1
        guard numberOfRows(inSection: 0) > 0 else { return }
        let lastIndexPath = IndexPath(item: numberOfRows(inSection: lastSection)-1, section: lastSection)
        scrollToRow(at: lastIndexPath, at: scrollPosition, animated: animated)
    }
}
